<?php
	require_once("baseobj.php");
	
class Project extends BaseObj {
	public $ProjectId = 0;
	public $Name = "";
	public $Description = "";
	public static $Select = "SELECT PROJECTID, NAME, DESCRIPTION, to_char(CREATED,'MM/DD/YYYY HH24:MI') CREATED, to_char(MODIFIED,'MM/DD/YYYY HH24:MI') MODIFIED FROM Project";
	
	public function delete() {
		$sql = "DELETE FROM PROJECT WHERE ProjectId = :prid";
		$conn = createConn();
		$stmt = oci_parse($conn, $sql);
		oci_bind_by_name($stmt, ':prid', $this->ProjectId);
		$cnt = oci_execute($stmt);
		oci_free_statement($stmt);
		oci_close($conn);
	}
	
	public static function getByProjectId($projectId){
			$sql = Project::$Select." WHERE ProjectId = :projectId";
			$conn = createConn();
			$stmt = oci_parse($conn, $sql);
			oci_bind_by_name($stmt, ':projectId', $projectId);
			$cnt = oci_execute($stmt);
			$obj = null;
			if($cnt > 0) {
				$row = oci_fetch_array($stmt, OCI_ASSOC+OCI_RETURN_NULLS);				
				$obj = new Project();
				$obj->load($row);
			}			
			oci_free_statement($stmt);
			oci_close($conn);
			return $obj;
		}
	
	public static function getForUser() {
		$arr = array();
		$i = 0;
		$sql = Project::$Select." ORDER BY Name";
		$conn = createConn();
		$stmt = oci_parse($conn, $sql);

		$cnt = oci_execute($stmt);
		
		if($cnt > 0) {				
			while($row = oci_fetch_array($stmt, OCI_ASSOC+OCI_RETURN_NULLS)) {
				$obj = new Project();
				$obj->load($row);
				$arr[$i] = $obj;
				$i++;
			}
		}			
		oci_free_statement($stmt);
		oci_close($conn);
		
		return $arr;
	}
	
	public function load($row){			
		$this->ProjectId = $row["PROJECTID"];
		$this->Name = $row["NAME"];
		$this->Description = $row["DESCRIPTION"];
		$this->Created = $row["CREATED"];
		$this->Modified = $row["MODIFIED"];
	}
	
	public static function nextId() {
		$sql = "SELECT seq.nextval FROM Dual"; 
		$conn = createConn();
		$stmt = oci_parse($conn, $sql);
		oci_execute($stmt);
		$row = oci_fetch_array($stmt, OCI_ASSOC+OCI_RETURN_NULLS);
		$v = $row["NEXTVAL"];
		oci_free_statement($stmt);
		oci_close($conn);
		return $v;
	}
	
	public function save() { 
		$sql = null;
		$stmt = null;
		$conn = null;
		
		$this->Modified = new DateTime();
		
		if($this->ProjectId == null || $this->ProjectId == 0) {
			$this->ProjectId = Project::nextId();
			$sql = "INSERT INTO Project (ProjectId, Name, Description) VALUES (:projectId, :name, :description)";			
		}
		else {  				
			$sql = "UPDATE Project SET Name = :name, Description = :description WHERE ProjectId = :projectId";		
		}
		$conn = createConn();
		$stmt = oci_parse($conn, $sql);
		oci_bind_by_name($stmt, ':projectId', $this->ProjectId);
		oci_bind_by_name($stmt, ':name', $this->Name);
		oci_bind_by_name($stmt, ':description', $this->Description);
		$cnt = oci_execute($stmt);
		oci_free_statement($stmt);
		oci_close($conn);
		
		return $cnt > 0;
	} 
}
?>